<template>
  <div class="inventory-check-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>库存盘点</span>
          <el-button type="primary" @click="handleCreate">新建盘点单</el-button>
        </div>
      </template>

      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="盘点单号">
          <el-input v-model="queryForm.checkNo" placeholder="请输入盘点单号" />
        </el-form-item>
        <el-form-item label="仓库">
          <el-select
            v-model="queryForm.warehouse"
            placeholder="请选择仓库"
            clearable
          >
            <el-option
              v-for="item in warehouseOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="盘点类型">
          <el-select v-model="queryForm.type" placeholder="请选择盘点类型">
            <el-option label="全面盘点" value="full" />
            <el-option label="动态盘点" value="dynamic" />
            <el-option label="抽样盘点" value="sample" />
          </el-select>
        </el-form-item>
        <el-form-item label="盘点日期">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态">
            <el-option label="待盘点" value="pending" />
            <el-option label="盘点中" value="processing" />
            <el-option label="待审核" value="toBeAudited" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="expand">
          <template #default="props">
            <el-table :data="props.row.items" border>
              <el-table-column prop="materialCode" label="物料编码" />
              <el-table-column prop="materialName" label="物料名称" />
              <el-table-column prop="specification" label="规格型号" />
              <el-table-column prop="unit" label="单位" />
              <el-table-column prop="location" label="库位" />
              <el-table-column prop="batchNo" label="批次号" />
              <el-table-column prop="systemQuantity" label="账面数量" />
              <el-table-column prop="actualQuantity" label="实盘数量" />
              <el-table-column prop="diffQuantity" label="差异数量" />
              <el-table-column prop="checkStatus" label="盘点状态">
                <template #default="scope">
                  <el-tag :type="getCheckStatusType(scope.row.checkStatus)">
                    {{ getCheckStatusText(scope.row.checkStatus) }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="checkNo" label="盘点单号" width="180" />
        <el-table-column prop="warehouse" label="仓库" width="120" />
        <el-table-column prop="type" label="盘点类型" width="100">
          <template #default="scope">
            {{ getTypeText(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="checkDate" label="盘点日期" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="120" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleEdit(scope.row)"
              v-if="scope.row.status === 'pending'"
              >编辑</el-button
            >
            <el-button
              link
              type="primary"
              @click="handleCheck(scope.row)"
              v-if="['pending', 'processing'].includes(scope.row.status)"
              >盘点</el-button
            >
            <el-button
              link
              type="primary"
              @click="handleAudit(scope.row)"
              v-if="scope.row.status === 'toBeAudited'"
              >审核</el-button
            >
            <el-button link type="primary" @click="handleView(scope.row)"
              >查看</el-button
            >
            <el-button
              link
              type="danger"
              @click="handleCancel(scope.row)"
              v-if="scope.row.status === 'pending'"
              >取消</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新建盘点单' : '编辑盘点单'"
      width="80%"
    >
      <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="仓库" prop="warehouse">
              <el-select
                v-model="form.warehouse"
                placeholder="请选择仓库"
                @change="handleWarehouseSelect"
              >
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="盘点类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择盘点类型">
                <el-option label="全面盘点" value="full" />
                <el-option label="动态盘点" value="dynamic" />
                <el-option label="抽样盘点" value="sample" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="盘点日期" prop="checkDate">
              <el-date-picker
                v-model="form.checkDate"
                type="date"
                placeholder="请选择盘点日期"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="盘点范围">
          <el-table :data="form.items" border>
            <el-table-column type="selection" width="55" />
            <el-table-column prop="materialCode" label="物料编码" />
            <el-table-column prop="materialName" label="物料名称" />
            <el-table-column prop="specification" label="规格型号" />
            <el-table-column prop="unit" label="单位" />
            <el-table-column prop="location" label="库位" />
            <el-table-column prop="batchNo" label="批次号" />
            <el-table-column prop="systemQuantity" label="账面数量" />
          </el-table>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 盘点对话框 -->
    <el-dialog v-model="checkDialogVisible" title="库存盘点" width="80%">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="盘点单号">{{
          currentCheck.checkNo
        }}</el-descriptions-item>
        <el-descriptions-item label="仓库">{{
          currentCheck.warehouse
        }}</el-descriptions-item>
        <el-descriptions-item label="盘点类型">{{
          getTypeText(currentCheck.type)
        }}</el-descriptions-item>
      </el-descriptions>

      <el-table :data="checkForm.items" border class="mt-20">
        <el-table-column prop="materialCode" label="物料编码" />
        <el-table-column prop="materialName" label="物料名称" />
        <el-table-column prop="specification" label="规格型号" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column prop="location" label="库位" />
        <el-table-column prop="batchNo" label="批次号" />
        <el-table-column prop="systemQuantity" label="账面数量" />
        <el-table-column label="实盘数量" width="150">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.actualQuantity"
              :min="0"
              @change="handleActualQuantityChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="diffQuantity" label="差异数量" />
        <el-table-column label="备注" width="200">
          <template #default="scope">
            <el-input v-model="scope.row.remark" placeholder="请输入备注" />
          </template>
        </el-table-column>
      </el-table>

      <div class="dialog-footer mt-20">
        <el-button @click="checkDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCheckSubmit"
          >提交盘点</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 查询表单
const queryForm = reactive({
  checkNo: "",
  warehouse: "",
  type: "",
  dateRange: [],
  status: "",
});

// 表格数据
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 新建/编辑对话框
const dialogVisible = ref(false);
const dialogType = ref("create");
const form = reactive({
  warehouse: "",
  type: "",
  checkDate: "",
  items: [],
  remark: "",
});

// 盘点对话框
const checkDialogVisible = ref(false);
const currentCheck = ref({});
const checkForm = reactive({
  items: [],
});

// 状态转换
const getTypeText = (type) => {
  const map = {
    full: "全面盘点",
    dynamic: "动态盘点",
    sample: "抽样盘点",
  };
  return map[type] || type;
};

const getStatusType = (status) => {
  const map = {
    pending: "info",
    processing: "warning",
    toBeAudited: "warning",
    completed: "success",
    cancelled: "danger",
  };
  return map[status] || "info";
};

const getStatusText = (status) => {
  const map = {
    pending: "待盘点",
    processing: "盘点中",
    toBeAudited: "待审核",
    completed: "已完成",
    cancelled: "已取消",
  };
  return map[status] || status;
};

const getCheckStatusType = (status) => {
  const map = {
    pending: "info",
    checked: "success",
    difference: "warning",
  };
  return map[status] || "info";
};

const getCheckStatusText = (status) => {
  const map = {
    pending: "待盘点",
    checked: "已盘点",
    difference: "有差异",
  };
  return map[status] || status;
};

// 查询方法
const handleSearch = () => {
  // 实现查询逻辑
};

const handleReset = () => {
  queryForm.checkNo = "";
  queryForm.warehouse = "";
  queryForm.type = "";
  queryForm.dateRange = [];
  queryForm.status = "";
  handleSearch();
};

// 新建/编辑方法
const handleCreate = () => {
  dialogType.value = "create";
  form.warehouse = "";
  form.type = "";
  form.checkDate = "";
  form.items = [];
  form.remark = "";
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  dialogType.value = "edit";
  Object.assign(form, row);
  dialogVisible.value = true;
};

const handleWarehouseSelect = (value) => {
  // 根据仓库加载库存数据
  form.items = [];
  // 实现库存数据加载逻辑
};

const handleSubmit = async () => {
  try {
    // 验证表单
    await formRef.value.validate();

    if (form.items.length === 0) {
      ElMessage.warning("请选择盘点物料");
      return;
    }

    // 实现保存逻辑
    ElMessage.success(dialogType.value === "create" ? "创建成功" : "更新成功");
    dialogVisible.value = false;
    handleSearch();
  } catch (error) {
    console.log("表单验证失败", error);
  }
};

// 盘点方法
const handleCheck = (row) => {
  currentCheck.value = row;
  checkForm.items = row.items.map((item) => ({
    ...item,
    actualQuantity: 0,
    diffQuantity: 0,
    remark: "",
  }));
  checkDialogVisible.value = true;
};

const handleActualQuantityChange = (row) => {
  row.diffQuantity = row.actualQuantity - row.systemQuantity;
};

const handleCheckSubmit = () => {
  // 验证是否有盘点数据
  const hasChecked = checkForm.items.some((item) => item.actualQuantity > 0);
  if (!hasChecked) {
    ElMessage.warning("请输入实盘数量");
    return;
  }

  // 实现盘点提交逻辑
  ElMessage.success("盘点提交成功");
  checkDialogVisible.value = false;
  handleSearch();
};

// 审核方法
const handleAudit = (row) => {
  ElMessageBox.confirm("确认审核通过该盘点单？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 实现审核逻辑
    ElMessage.success("审核成功");
    handleSearch();
  });
};

// 取消方法
const handleCancel = (row) => {
  ElMessageBox.confirm("确认取消该盘点单？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 实现取消逻辑
    ElMessage.success("已取消");
    handleSearch();
  });
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleSearch();
};
</script>

<style scoped>
.inventory-check-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.mt-20 {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
